<?php


namespace app\api\controller\xiluedu;


use addons\xiluedu\controller\WeixinMini;
use app\common\controller\Api;
use app\common\model\xiluedu\FooterView;
use app\common\model\xiluedu\OfflineCourse AS OfflineCourseModel;
use app\common\model\xiluedu\OfflineCoursePeriod;
use think\Exception;
use function fast\array_get;

class OfflineCourse extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['lists','detail'];


    /**
     * 课程列表
     */
    public function lists(){
        $params = $this->request->param('');
        $this->success('查询成功',OfflineCourseModel::searchLists($params));
    }

    /**
     * 课程详情
     * @throws \think\exception\DbException
     */
    public function detail(){
        $params = $this->request->param('');
        $offline_course_id = array_get($params,'offline_course_id');
        if(!$offline_course_id){
            $this->error('非法参数');
        }
        $course = OfflineCourseModel::with(['teacher'=>function($query){
            $query->withField('id,name,job,thumb_image');
        }])
            ->field('weigh,createtime,updatetime,deletetime',true)->where('id',$offline_course_id)->find();
        if(!$course){
            $this->error('课程不存在');
        }
        $left_count = $course->total_count - $course->enroll_count;
        $course->left_count = $left_count < 0 ? $left_count :$left_count;
//        $course->enroll_status = $this->auth->isLogin()
//            ? \app\common\model\xiluedu\OfflineOrder::where('course_id',$offline_course_id)->where('user_id',$this->auth->id)->where('pay_status','1')->count() : 0;
        $course->enroll_status = 0;

        $wxmini = new WeixinMini();
        $res = $wxmini->getUnlimited('offline_id='.$course->id,'pages/offline_course_detail/offline_course_detail');
        if($res){
            $root = '.';
            $filename = md5(mt_rand()).'.png';
            $path = "/uploads/".date('Ymd').'/';
            if (!file_exists($root . $path)) {
                @mkdir($root . $path, 0777, true);
            }
            $qrcode = $path.$filename;
            if(!get_addon_config('alioss')){
                file_put_contents($root.$qrcode,$res);
            }else{
                Common::uploadAlioss($path, $res);
            }
            $course->qrcode = cdnurl($qrcode,true);
        }

        #足迹
        if($this->auth->isLogin()){
            try {
                FooterView::viewFooter($this->auth->id,$offline_course_id,FooterView::TYPE_OFFLINE);
            }catch (Exception $e){
                //$this->error($e->getMessage());
            }
        }

        $this->success('查询成功',$course);
    }
}